<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
    <div class="wrapper">
      <div class="input-row">
        <el-form :inline="true" :model="formInline" @submit.native.prevent>
          <el-form-item label="名称">
            <el-input style="width: 140px" size="small" clearable v-model="formInline.name" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item label="编号">
            <el-input style="width: 140px" size="small" clearable v-model="formInline.code" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item label="版本">
            <el-input style="width: 140px" size="small" clearable v-model="formInline.version" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" size="small">查询</el-button>
            <el-button @click="resetQuery" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-tabs v-model="standardType" type="card" @tab-click="handleTabClick">
        <el-tab-pane name="enterprise" label="内部文件">
          <el-table v-loading="loading" :data="tableData" class="ins-table" max-height="500">
            <el-table-column prop="name" label="名称"> </el-table-column>
            <el-table-column prop="code" width="200" label="编号"> </el-table-column>
            <el-table-column prop="version" width="200" label="版本"> </el-table-column>
            <el-table-column width="160" label="插入" v-if="referenceType === 'refdoc'">
              <template slot-scope="scope">
                <el-button type="text" size="mini" :disabled="!scope.row.version" @click="insert(scope.row, true)"
                  >带版本</el-button
                >
                <el-button type="text" size="mini" @click="insert(scope.row)">不带版本</el-button>
              </template>
            </el-table-column>
            <el-table-column width="100" label="操作" v-else>
              <template slot-scope="scope">
                <el-button type="text" size="mini" :disabled="!scope.row.version" @click="view(scope.row)">更多</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane name="external" label="外部文件">
          <el-table v-loading="loading" :data="tableData" class="ins-table" max-height="500">
            <el-table-column prop="name" label="名称"> </el-table-column>
            <el-table-column prop="code" width="200" label="编号"> </el-table-column>
            <el-table-column prop="version" width="200" label="版本"> </el-table-column>
            <el-table-column width="160" label="插入" v-if="referenceType === 'refdoc'">
              <template slot-scope="scope">
                <el-button type="text" size="mini" :disabled="!scope.row.version" @click="insert(scope.row, true)"
                  >带版本</el-button
                >
                <el-button type="text" size="mini" @click="insert(scope.row)">不带版本</el-button>
              </template>
            </el-table-column>
            <el-table-column width="100" label="操作" v-else>
              <template slot-scope="scope">
                <el-button type="text" size="mini" :disabled="!scope.row.version" @click="view(scope.row)">更多</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-pagination
        v-if="total"
        layout="prev, pager, next"
        :page-size="10"
        :total="total"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-dialog>
</template>

<script>
import tinymce from 'tinymce'
import { v4 as uuid } from 'uuid'
import { getStandardPage, getStandardContent } from '@/api'
import { Message } from 'element-ui'
import { getLinkUrl } from '@/utils/helpers'

export default {
  name: 'ReferenceDialog',
  data() {
    return {
      total: 0,
      currentPage: 1,
      tableData: [],
      formInline: {
        name: undefined,
        code: undefined
      },
      loading: false,
      standardType: 'enterprise',
      dialogVisible: false
    }
  },
  computed: {
    referenceType() {
      return this.$store.state.xmleditor.referenceType
    },
    title() {
      switch (this.referenceType) {
        case 'refdoc':
          return '引用文件编号'
        default:
          return '引用内容编号'
      }
    }
  },
  methods: {
    resetQuery() {
      this.currentPage = 1
      this.formInline = {
        name: undefined,
        code: undefined
      }
      this.handleFilter()
    },
    show() {
      this.resetQuery()
      this.standardType = 'enterprise'
      this.dialogVisible = true
    },
    async handleFilter(e) {
      if (e) {
        this.currentPage = 1
      }
      const data = { ...this.formInline, pageSize: 10, pageNum: this.currentPage, status: 6 }
      if (this.standardType === 'external') {
        data.outStandard = true
      }
      this.loading = true
      const { count, list, pageNum } = await getStandardPage(data)
      this.loading = false
      this.total = count
      this.tableData = list
      this.currentPage = pageNum
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.handleFilter()
    },
    handleTabClick(tab, event) {
      this.standardType = tab.name
      this.handleFilter(event)
    },
    insert(row, withVersion = false) {
      const refdate = ''
      const name = row.name?.replace(/"/g, '') || ''
      let content = row.code
      if (withVersion) {
        content += `&nbsp;${row.version}版&nbsp;《${name}》`
      } else {
        content += `&nbsp;《${name}》`
      }
      tinymce.activeEditor.insertContent(
        `<span
        class="noneditable ref-link ${row.mainContentId ? '' : 'ref-disabled'}"
        contenteditable="false"
        data-type="refdoc"
        data-refname="${name}"
        data-standardid="${row.id}"
        data-maincontentid="${row.mainContentId}"
        data-refclassification="${row.classification}"
        data-refdate="${refdate}"
        data-link-url="${getLinkUrl(row.mainContentId) || ''}"
        data-docno="${row.docNo || ''}"
        data-refversion="${row.version}"
        data-refcontent="${content}"
        data-refcode="${row.code}"
        data-id="${uuid()}"
        data-category="${row.category}"
      >${content}</span>`
      )
      tinymce.activeEditor.fire('addNewRef', { reftype: 'refdoc', code: row.code, version: row.version })
      Message.success('插入成功')
    },
    async view(row) {
      if (!row.docNo) {
        Message.warning('缺少历史结构化数据')
        return
      }
      const res = await getStandardContent({ docNo: row.docNo })
      if (!res.content) {
        return Message.error('文档内容不存在')
      }
      const doc = JSON.parse(res.content)
      const pageList = doc.pageList.filter((item) => item.pageType === 'content')
      const blockList = pageList.reduce((acc, cur) => [...acc, ...cur.blockList], [])
      this.$store.commit('xmleditor/SET_CURRENT_STANDARD', row)
      this.$store.commit('xmleditor/SET_CONTENT_BLOCKLIST', blockList)
      this.$store.commit('xmleditor/SET_REF_LANGUAGE_TYPE', doc?.languageType)
      this.$emit('show-content-dialog')
    },
    handleClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.ins-table {
  width: 100%;
}
::v-deep .el-dialog {
  min-width: 800px;
}
::v-deep .el-dialog__body {
  padding-top: 0;
  padding-bottom: 10px;
}
</style>
